package com.ocom.app.controller;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSON;
import com.ocom.app.feignclient.CompanyFeignClient;
import com.ocom.app.feignclient.MqSimpleFeignClint;
import com.ocom.common.entity.master.EntityMngAccountInfo;
import com.ocom.common.entity.master.EntityMngUserInfo;
import com.ocom.common.enums.ResultEnum;
import com.ocom.common.request.company.MngAccountInfoRequest;
import com.ocom.common.request.simple.SmsRequest;
import com.ocom.common.resp.Result;
import com.ocom.common.utils.ResultUtil;
import com.ocom.common.utils.StringUtil;
import com.ocom.redis.util.RedisUtil;
import com.ocom.security.authentication.YoCiUser;
import com.ocom.security.utils.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.Objects;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
public class MngAccountInfoController {

  @Autowired
  private CompanyFeignClient companyFeignClient;

  @Autowired
  private RedisUtil redisUtil;

  @Autowired
  private RedisTemplate redisTemplate;

  @Autowired
  private MqSimpleFeignClint mqSimpleFeignClint;

  @GetMapping("/sendsms")
  public Result sendSms(@RequestParam("telephone") String telephone,
      @RequestParam(name = "role", required = false,
          defaultValue = "41"
      ) String role) {

    // 校验手机号是否合法
    if (StringUtil.isEmpty(telephone) || !StringUtil.isPhone(telephone)) {
      return ResultUtil.error(ResultEnum.Err_4705);
    }

    // 1，通过redis验证上一条短信间隔是否超过（通过redis的锁实现）
    // 2，未超过返回 验证码发送太频繁，请稍后重试。
    if (!redisUtil.lock("app:smsPhone:" + telephone, 60)) {
      return ResultUtil.error(ResultEnum.Err_4700);
    }

    // 3，验证手机号是否超过当日发送最大值。(通过redis实现)
    //checkSendLimit
    Integer maxSendCount = 20;

    String limitKey = "send:telephone:limit:";
    Object o = redisTemplate.opsForValue().get(limitKey + telephone);

    Integer count = ObjectUtil.isNotNull(o) ? (Integer) o : 0;
    if (count >= maxSendCount) {
      return ResultUtil.error(ResultEnum.Err_4701);
    }
    // 验证码一天
    redisTemplate.opsForValue().set(limitKey + telephone, ++count, 86400l, TimeUnit.SECONDS);

    // 4，超过或者无锁 调用 3.0微服务 - 单位3.33
    Result userByNameAndRole = companyFeignClient.getAccountAndRole(telephone, "41");
    EntityMngUserInfo entityMngUserInfo = JSON.parseObject(
        JSON.toJSONString(userByNameAndRole.getData()), EntityMngUserInfo.class);
    if (Objects.isNull(entityMngUserInfo)) {
      // 如返回为空，则提示 手机未绑定商户管理员
      return ResultUtil.error(ResultEnum.Err_4702);
    }
    String codeKey = "send:telephone:code:";
    // 5，如返回一条正确的数据，则调发送短信的接口。并将发送的短信验证码写入redis
    String code = RandomUtil.randomNumbers(6);

    log.info("手机号:{}发送短信验证码:{}", telephone, code);

    // 验证码5分钟
    redisTemplate.opsForValue().set(codeKey + telephone, code, 300l, TimeUnit.SECONDS);
    // 发送短信
    SmsRequest smsRequest = new SmsRequest();
    smsRequest.setSecretId("AKIDcLzhN0a8e8eChEnaQG8zpifcabfnu5JX");
    smsRequest.setSecretKey("Kh6VozznPn13ECwSlphN9jCVaRLTPIPa");
    smsRequest.setSignName("鑫澳康科技");
    smsRequest.setSdkAppId("1400314290");
    smsRequest.setTemplateId("2508963");
    smsRequest.setPhone(telephone);
    smsRequest.getParams().add(code);
    mqSimpleFeignClint.FySms(smsRequest);

    return ResultUtil.success();
  }

  @PostMapping("/account")
  public Result account(@RequestBody MngAccountInfoRequest request) {
    Result result = companyFeignClient.selectAccountsByPhone(request);
    return ResultUtil.success(result.getData());
  }


  @PostMapping("/add/account")
  public Result addMngAccount(@RequestBody MngAccountInfoRequest mngAccountInfoRequest) {
    if (StringUtil.isEmpty(mngAccountInfoRequest.getPhone()) || !StringUtil.isPhone(
        mngAccountInfoRequest.getPhone())) {
      return ResultUtil.error(ResultEnum.Err_4705);
    }
    Result result = companyFeignClient.addMngAccount(mngAccountInfoRequest);
    return ResultUtil.success(result.getData());
  }


}
